package com.habdqn.studentmanager.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.habdqn.studentmanager.bean.Product;
import com.habdqn.studentmanager.constant.LogType;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.mapper.ClassesMapper;
import com.habdqn.studentmanager.mapper.ProductMapper;
import com.habdqn.studentmanager.service.ProductService;
import com.habdqn.studentmanager.util.SystemLogger;

@Service
public class ProductServiceImpl implements ProductService {

	private Logger logger = Logger.getLogger(ProductServiceImpl.class);

	@Resource
	private ProductMapper productMapper;

	@Resource
	private ClassesMapper classesMapper;

	@Resource
	private SystemLogger systemLogger;

	@Override
	public PageInfo<Product> findProductList(Integer pageNum,Integer pageSize,Product bean) {
		// 有不需要分页的场景
		if (null != pageNum && null != pageSize) {
			PageHelper.startPage(pageNum, pageSize);			
		}
		List<Product> list = productMapper.findList(bean);
		PageInfo<Product> page = new PageInfo<Product>(list);
		return page;
	}

	@Override
	public void addProduct(Product bean) {
		try {
			productMapper.insert(bean);
			systemLogger.record(LogType.AddType, "新增产品:" + bean.getId());
		}
		catch (DuplicateKeyException e) {
			logger.debug("duplicateKey: " + bean.getId(), e);
			throw new StudentException("产品名称重复，请重新输入", e);
		}
		catch (RuntimeException e) {
			logger.error("查询产品列表失败！" + e);
			throw new StudentException("查询产品列表失败！", e);
		}

	}

	@Override
	public void delete(Product bean) {

		// 检查是否有与班级的关联关系
		long count = PageHelper.count(new ISelect() {
			
			@Override
			public void doSelect() {
				classesMapper.findListByProduct(bean);
			}
		});

		if (count > 0) {
			throw new StudentException("有班级关联该产品, 无法删除");
		}

		try {
			productMapper.delete(bean);
		}
		catch (RuntimeException e) {
			logger.error("system error", e);
			throw new StudentException("系统错误, 删除产品失败");
		}

		systemLogger.record(LogType.DelType, "删除产品:" + bean.getId());
	}

	@Override
	public void update(Product bean) {
		
		try {
			productMapper.update(bean);
			systemLogger.record(LogType.UpdateType, "更新产品:" + bean.getId());
		}
		catch (RuntimeException e) {
			logger.error("error", e);
			throw new StudentException("更新产品失败", e);
		}
	}

	@Override
	public Product findById(Integer id) {
		Product bean = null;
		try {
			bean = productMapper.findById(id);
		}
		catch (RuntimeException e) {
			logger.error("获取产品失败", e);
			throw new StudentException("获取产品失败", e);
		}
		return bean;
	}
}
